package com.junzhiit.nengji.cms.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.bo.OrdersGoodsBO;
import com.junzhiit.nengji.cms.service.OrdersGoodsService;
import com.junzhiit.nengji.cms.web.exception.GoodsNotFoundException;
import com.junzhiit.nengji.cms.web.exception.OrdersGoodsNotFoundException;
import com.junzhiit.nengji.cms.web.exception.RefundMoneyFailException;
import com.junzhiit.nengji.cms.web.util.ViewObjectUtil;
import com.junzhiit.nengji.cms.web.util.tools.NumberUtils;
import com.junzhiit.nengji.cms.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.cms.web.util.wechat.bean.RefundOrder;
import com.junzhiit.nengji.cms.web.util.wechat.bean.RefundResult;
import com.junzhiit.nengji.cms.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.cms.web.vo.OrdersRefundVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.dao.GoodsDAO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.OrdersGoodsDAO;
import com.junzhiit.nengji.dao.OrdersRefundDAO;
import com.junzhiit.nengji.dao.ShopClientDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.model.Goods;
import com.junzhiit.nengji.model.Orders;
import com.junzhiit.nengji.model.OrdersGoods;
import com.junzhiit.nengji.model.OrdersRefund;
import com.junzhiit.nengji.model.ShopClient;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.enums.ApplyRefundIdentity;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.OrderStatus;
import com.junzhiit.nengji.model.enums.OrdersRefundStatus;
import com.junzhiit.nengji.model.enums.PayWay;

@Service
public class OrdersGoodsServiceImpl extends BaseServiceImpl implements OrdersGoodsService {

	@Autowired
	private OrdersGoodsDAO ordersGoodsDAO;

	@Autowired
	private GoodsDAO goodsDAO;
	
	@Autowired
	private OrdersDAO ordersDAO;
	
	@Autowired
	private OrdersRefundDAO ordersRefundDAO;
	
	@Autowired
	private UserConfigDAO userConfigDAO;
	
	@Autowired
	private ShopClientDAO shopClientDAO;
	
	@Override
	public Map<String, Object> findAll(DataTablesParamVO dtp, String orderId) {
		List<OrdersGoodsBO> list = ordersGoodsDAO.getOrderGoodsOrderId(orderId);
		int totalCount = ordersGoodsDAO.getTotalCount(orderId);
		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}

	@Override
	public ResultVO getOrderCountByGoodsId(String goodsId) {
		ResultVO result = new ResultVO();
		Goods goods = goodsDAO.query(goodsId);
		if (goods == null) {
			throw new GoodsNotFoundException("商品不存在");
		}
		int data = ordersGoodsDAO.getOrderCountByGoodsId(goodsId);
		result.setData(data);
		return result;

	}

	@Override
	public ResultVO update(OrdersRefundVO ordersRefundVO) {
		ResultVO result = new ResultVO();
		//更新订单商品状态
		boolean flag = true;
		OrdersGoods ordersGoods = ordersGoodsDAO.query(ordersRefundVO.getOrdersGoodsId());
		if(ordersGoods == null){
			throw new OrdersGoodsNotFoundException("订单商品不存在");
		}
		if(goodsDAO.query(ordersGoods.getGoodsId())==null){
			throw new GoodsNotFoundException("商品不存在");
		}
		ordersGoods.setIsRefundMoney(Is.YES.toIntValue());
		ordersGoodsDAO.update(ordersGoods);
		//更新订单状态
		List<OrdersGoodsBO> list = ordersGoodsDAO.getOrderGoodsOrderId(ordersRefundVO.getOrdersId());
		Orders orders = ordersDAO.query(ordersRefundVO.getOrdersId());
		for(int i=0;i<list.size();i++){
			if(list.get(i).getIsRefundMoney() == Is.NO.toIntValue()){
				flag=false;
				break;
			}
		}
		if(flag){
			orders.setStatus(OrderStatus.FAILIN.toIntValue());
			ordersDAO.update(orders);
		}
		//插入退款记录
		OrdersRefund ordersRefund = new OrdersRefund();
		OrdersGoodsBO goods = ordersGoodsDAO.getOrdersGoods(ordersRefundVO.getOrdersGoodsId());
		BeanUtils.copyProperties(ordersRefundVO, ordersRefund);
		if(goods.getIsRefundGoods() == Is.YES.toIntValue()){
			ordersRefund.setGoodsRefundId(goods.getGoodsRefundId());
		}
		ordersRefund.setShopId(goods.getShopId());
		ordersRefund.setStatus(OrdersRefundStatus.SHOP_AGREE.toIntStatus());
		ordersRefund.setType(ApplyRefundIdentity.SHOP.toIntValue());
		ordersRefund.setShopDealTime(new Date());
		ordersRefund.setRefundNumber(NumberUtils.getMchBillno());
		ordersRefundDAO.insert(ordersRefund);
		return result;
	}

	@Override
	public ResultVO findInfo(String ordersGoodsId) {
		ResultVO result = new ResultVO();
		OrdersGoods ordersGoods=ordersGoodsDAO.query(ordersGoodsId);
		Double price = ordersGoods.getPrice();
		result.setData(price);
		return result;
	}

	@Override
	public ResultVO applyRefund(OrdersRefundVO ordersRefundVO) {
		ResultVO result = new ResultVO();
		boolean flag = true;
		Orders orders = ordersDAO.query(ordersRefundVO.getOrdersId());
		RefundResult refundResult = new RefundResult();
		UserConfig userConfig = userConfigDAO.getUserConfig(orders.getUserId());
		if(orders.getPayWay()==PayWay.WECHAT.toIntValue()){//微信支付退款
			RefundOrder refundOrder = new RefundOrder();
			refundOrder.setTransactionId(orders.getTransactionNumber());
			refundOrder.setOutRefundNo(NumberUtils.getMchBillno());
			refundOrder.setTotalFee(Math.round(orders.getPayMoney()*100));
			refundOrder.setRefundFee(Math.round(ordersRefundVO.getMoney()*100));
			refundOrder.setRefundDesc(ordersRefundVO.getReason());
			refundResult = WeChatUtils.refund(refundOrder);
			if(refundResult.getRefundId() == null){
				throw new RefundMoneyFailException("退款失败！");
			}
		}else if(orders.getPayWay()==PayWay.CASH.toIntValue()){
			userConfig.setCurrentMoney(userConfig.getCurrentMoney()+ordersRefundVO.getMoney());
			userConfigDAO.update(userConfig);
		}else if(orders.getPayWay()==PayWay.REDEEM.toIntValue()){
			userConfig.setWithdrawalMoney(userConfig.getWithdrawalMoney()+ordersRefundVO.getMoney());
			userConfigDAO.update(userConfig);
		}else if(orders.getPayWay()==PayWay.MEMBER.toIntValue()){
			ShopClient shopClient = shopClientDAO.findClientByUserId(orders.getUserId(),orders.getShopId());
			shopClient.setBalance(shopClient.getBalance()+ordersRefundVO.getMoney());
			shopClientDAO.update(shopClient);
		}
		
		//更新订单商品状态
		OrdersGoods ordersGoods = ordersGoodsDAO.query(ordersRefundVO.getOrdersGoodsId());
		if(ordersGoods == null){
			throw new OrdersGoodsNotFoundException("订单商品不存在");
		}
		if(goodsDAO.query(ordersGoods.getGoodsId())==null){
			throw new GoodsNotFoundException("商品不存在");
		}
		ordersGoods.setIsRefundMoney(Is.NO.toIntValue());
		ordersGoodsDAO.update(ordersGoods);
		//更新订单状态
		List<OrdersGoodsBO> list = ordersGoodsDAO.getOrderGoodsOrderId(ordersRefundVO.getOrdersId());
		for(int i=0;i<list.size();i++){
			if(list.get(i).getIsRefundMoney() == Is.NO.toIntValue()){
				flag=false;
				break;
			}
		}
		if(flag){
			orders.setStatus(OrderStatus.FAIL.toIntValue());
			ordersDAO.update(orders);
		}
		
		//插入退款表数据
		OrdersRefund ordersRefund = new OrdersRefund();
		OrdersGoodsBO goods = ordersGoodsDAO.getOrdersGoods(ordersRefundVO.getOrdersGoodsId());
		BeanUtils.copyProperties(ordersRefundVO, ordersRefund);
		if(goods.getIsRefundGoods() == Is.YES.toIntValue()){
			ordersRefund.setGoodsRefundId(goods.getGoodsRefundId());
		}
		ordersRefund.setShopId(goods.getShopId());
		ordersRefund.setStatus(OrdersRefundStatus.COMPLETE.toIntStatus());
		ordersRefund.setType(ApplyRefundIdentity.PLATFORM.toIntValue());
		ordersRefund.setPlatformTime(new Date());
		ordersRefund.setCompleteTime(new Date());
		if(orders.getPayWay()==PayWay.WECHAT.toIntValue()){
			ordersRefund.setRefundNumber(refundResult.getOutRefundNo());
			ordersRefund.setWechatRefundNumber(refundResult.getRefundId());
		}
		ordersRefundDAO.insert(ordersRefund);
		
		return result;
	}

	@Override
	public void updateCanRefund() {
		Date date = DateUtil.addDays(new Date(), -7);
		List<OrdersGoods> ordersGoods = ordersGoodsDAO.getCanRefundGoods(date);
		for(OrdersGoods goods : ordersGoods){
			goods.setCanRefund(Is.NO.toIntValue());
			ordersGoodsDAO.update(goods);
		}
	}
}
